﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace RS232_WPF
{
    public class RS232Helper
    {
        public SerialPort sp;//声明一个串口类
        public bool isHex = false;//十六进制显示标志位
        public event Action<string> ShowData;

        public RS232Helper(){
            sp = new SerialPort();
        }

        public string SetPortProperty(string comName,string portNum,string StopNum,string dataNum,string checkNum,bool isHexShow)//设置串口的属性
        {
            try
            {
                sp.PortName = comName.Trim();//串口名给了串口类
                //sp.BaudRate = Convert.ToInt32("");//Trim除去前后空格，讲文本转换为32位字符给予串口类 发送字符串
                if (checkNum.Trim() == "奇校验")
                {
                    sp.Parity = Parity.Odd;//将奇校验位给了sp的协议
                }
                else if (checkNum.Trim() == "偶校验")
                {
                    sp.Parity = Parity.Even;
                }
                else
                {
                    sp.Parity = Parity.None;
                }
                if (StopNum.Trim() == "1.5")
                {
                    sp.StopBits = StopBits.OnePointFive;//设置停止位有几位
                }
                else if (StopNum == "2")
                {
                    sp.StopBits = StopBits.Two;
                }
                else
                {
                    sp.StopBits = StopBits.One;
                }
                sp.DataBits = Convert.ToInt16(dataNum.Trim());//数据位
                sp.Encoding = Encoding.UTF8;//串口通信的编码格式
                sp.Open();
                Thread getData = new Thread(Received)
                {
                    IsBackground = true,
                    Priority = ThreadPriority.Highest
                };
                getData.Start();
                return null;
            }
            catch(Exception ex){
                return ex.Message.ToString();
            }
        }

        private void Received()
        {
            while (sp.IsOpen)
            {
                Thread.Sleep(1000);
                // if (isHex == false)
                // {
                //     try
                //     {
                //         Byte[] ReceivedData = new Byte[sp.BytesToRead]; //创建接收字节数组
                //         sp.Read(ReceivedData, 0, ReceivedData.Length); //读取所接收到的数据
                //         String RecvDataText = null;
                //         for (int i = 0; i < ReceivedData.Length - 1; i++)
                //         {
                //             RecvDataText += ReceivedData[i].ToString();
                //         }
                //         ShowData?.BeginInvoke(sp.ReadLine(), null, null);

                //     }
                //     catch
                //     {

                //     }
                // }
                // else
                // {
                //     Byte[] ReceivedData = new Byte[sp.BytesToRead]; //创建接收字节数组
                //     sp.Read(ReceivedData, 0, ReceivedData.Length); //读取所接收到的数据
                //     String RecvDataText = null;
                //     for (int i = 0; i < ReceivedData.Length - 1; i++)
                //     {
                //         RecvDataText += ("0x" + ReceivedData[i].ToString("X2") + "");
                //     }
                //     ShowData?.BeginInvoke(RecvDataText, null, null);
                // }
                //// sp.DiscardInBuffer(); //丢弃接收缓冲区数据
                ///


                try
                {
                    byte[] a = new byte[sp.BytesToRead];//读出缓冲区串口通信的字节
                    sp.Read(a, 0, a.Length);//写入sp
                    if(a.Length>0)
                    {
                        string my2 = Encoding.UTF8.GetString(a);
                        string b = "";
                        if (isHex)
                        {
                            b = ASCIIToHex(my2);
                        }
                        else
                        {
                            b = my2;
                        }
                        ShowData?.BeginInvoke(b + "\r\n", null, null); ;
                    }
                }
                catch
                {
                    ShowData?.BeginInvoke("接收失败" + "\r\n", null, null); ;
                }
            }
        }

        public string ASCIIToHex(string my2)
        {
            try
            {
                byte[] a = Encoding.UTF8.GetBytes(my2.Trim());
                string mystr1 = "";
                for (int i = 0; i < a.Length; i++)
                {
                    mystr1 += a[i].ToString("X2") + " ";
                }
                return mystr1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("转换失败！" + ex.Message, "错误提示");
                return my2;
            }


        }

        public string HexToASCII(string str)
        {
            try
            {
                string[] mystr1 = str.Trim().Split(' ');
                byte[] t = new byte[mystr1.Length];
                for (int i = 0; i < t.Length; i++)
                {
                    t[i] = Convert.ToByte(mystr1[i], 16);
                }
                return Encoding.UTF8.GetString(t);

            }
            catch (Exception ex)
            {
                MessageBox.Show("转换失败！" + ex.Message, "错误提示");
                return str;
            }
        }
        public List<string> CheckPort()//检查串口是否可用
        {
            List<string> comList=new List<string>();
            bool havePort = false;
            string[] a = SerialPort.GetPortNames();
            if (a != null)
            {

                for (int i = 0; i < a.Length; i++)
                {
                    bool use = false;
                    try
                    {
                        SerialPort t = new SerialPort(a[i]);
                        sp.Open();
                        sp.Close();
                        use = true;
                    }
                    catch
                    {
                    }
                    if (use)
                    {
                        comList.Add(a[i]);
                        havePort = true;
                    }
                }
            }
            if (havePort)
            {
                MessageBox.Show("有可用串口...", "提示");
            }
            else
            {
                MessageBox.Show("无可用串口...", "错误");
            }

            return comList;
        }
    }
}
